package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信扫码登录")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation("获取微信登录参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session) throws UnsupportedEncodingException {
        String redirectUrl  = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", redirectUrl);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return R.ok().data(map);
    }

    @ApiOperation(value = "回调接口")
    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {
        //1.获取授权验证码参数，非空校验
        if(StringUtils.isEmpty(code)){
            throw new YyghException(20001, "微信授权登陆失败");
        }
        //2.根据参数访问微信接口获取access_token，openid
        //2.1拼写url
       //方式一 String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                //"appid=APPID&secret=SECRET&code=" + code + "&grant_type=authorization_code";
        //方式二
        StringBuffer baseAccessTokenUrl   = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        //2.2借助工具发送请求获取响应
        try {
            String accessTokenStr  = HttpClientUtils.get(accessTokenUrl);
            //2.3转换响应类型获取参数
            JSONObject accessTokenJson = JSONObject.parseObject(accessTokenStr);
            String accessToken = accessTokenJson.get("access_token").toString();
            String openid = accessTokenJson.get("openid").toString();
            //3.根据openid查询用户信息
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("openid", openid);
            UserInfo userInfo = userInfoService.getOne(wrapper);
            //4.信息为空走注册步骤
            if (userInfo==null){
                //4.1注册需要访问微信接口，用access_tokne，openid获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String userInfoStr   = HttpClientUtils.get(userInfoUrl);
                String nickname = JSONObject.parseObject(userInfoStr).get("nickname").toString();
                String headimgurl = JSONObject.parseObject(userInfoStr).get("headimgurl").toString();
                userInfo = new UserInfo();
                userInfo.setOpenid(openid);
                userInfo.setNickName(nickname);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);

            }
            //5.判断用户的状态，0：锁定，取消登录
            if (userInfo.getStatus().intValue() == 0) {
                throw new YyghException(20001, "该用户已被锁定");
            }
            //6.如果第一次注册登录，需要绑定手机号
            Map<String,String> map = new HashMap<>();
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", openid);
            }else {
                map.put("openid", "");
            }
            //7.补全用户信息，走登录步骤
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("name", name);
            map.put("token",token);
            //8.重定向到指定页面
            return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+
                    "&openid="+map.get("openid")
                    +"&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
}
